<?php
namespace app\common\logic;
use think\facade\Db;

class MemberLevelLogic{
	public static $init;
	static function init(){
		if (!isset(self::$init)) {//判断是否以前创建了当前类的实例
            $c = __CLASS__;//获取类名
            self::$init = new static;//如果没有创建，实例化当前类，这里实现类只实例化一次
        }
        return self::$init;//返回类的实例
	}

	//用户等级处理
	function levelProcess($member_id=0, $amount=0){
		if(!$member_id){
			return 1;
		}
		//获取年月
		$year = date('Y');
		$mouth = date('m');
		//查询本月记录
		$info = Db::name('member_recharge_year_mouth')
				->where('year', $year)
				->where('mouth', $mouth)
				->where('member_id', $member_id)
				->find();
		if(!$info){
			$info = [];
			$info['member_id'] = $member_id;
			$info['year'] = $year;
			$info['mouth'] = $mouth;
			$info['amount'] = 0;
			$info['current_level'] = 1;
			$info['current_amount'] = 0;
			$info['next_level'] = 1;
			$info['next_amount'] = 0;
			$info['create_time'] = date('Y-m-d H:i:s');
			//新增本月的记录
			$info['id'] = Db::name('member_recharge_year_mouth')->insertGetId($info);
		}
		//本次金额
		if(!$amount){
			return 1;
		}
		//当前总金额，已经累计的金额+本次的金额
		$current_all_amount = $amount + $info['amount'];


		$lists = Db::name('member_grade')
					->field('id,level,grade_name,recharge_amount')
					->where('status',1)
					->order('level desc')
					->select();

		$current_level = $info['current_level'];
		$current_amount = $info['current_amount'];

		$next_level = $info['next_level'];
		$next_amount = $info['next_amount'];
		// print_r($info);
		foreach($lists as $k=>$v){

			if($current_all_amount<$v['recharge_amount']){
				$next_level = $v['level'];  //下个等级
				$next_amount = $v['recharge_amount']; //下个等级金额
			}

			//当前总金额大于等级金额，则设置当前等级和当前金额为此
			if($current_all_amount>=$v['recharge_amount']){
				$current_level = $v['level'];
				$current_amount = $v['recharge_amount'];
				break;
			}
		}
		
		//修改记录
		$ud = [];
		$ud['amount'] = $current_all_amount;
		$ud['current_level'] = $current_level;
		$ud['current_amount'] = $current_amount;
		$ud['next_level'] = $next_level;
		$ud['next_amount'] = $next_amount;

		$rs = Db::name('member_recharge_year_mouth')->where('id', $info['id'])->update($ud);
		return 1;
		

	}

}